package com.aclass.xqx.classscreen.service;

import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Environment;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
import android.widget.Toast;

import com.aclass.xqx.classscreen.BaseApplication;
import com.aclass.xqx.classscreen.IMyAidlInterface;
import com.aclass.xqx.classscreen.MainActivity;
import com.aclass.xqx.classscreen.bean.API;
import com.aclass.xqx.classscreen.bean.VersionInfo;
import com.aclass.xqx.classscreen.db.CardDao;
import com.aclass.xqx.classscreen.db.CardStudent;
import com.aclass.xqx.classscreen.db.StudentSign;
import com.aclass.xqx.classscreen.utlis.AppUtlis;
import com.aclass.xqx.classscreen.utlis.AsyncTaskSoapUtil;
import com.aclass.xqx.classscreen.utlis.ClassCalendar;
import com.aclass.xqx.classscreen.utlis.Constant;
import com.aclass.xqx.classscreen.utlis.DialogUtlis;
import com.aclass.xqx.classscreen.utlis.OkhttPost;
import com.aclass.xqx.classscreen.utlis.PrefUtild;
import com.google.gson.Gson;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.FileCallBack;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import okhttp3.Call;
import okhttp3.Request;

import static android.content.ContentValues.TAG;

/**
 * Created by xqx on 2017/11/10.
 *
 */

public class RemoteService extends Service {
    private MyBinder binder;
    private ServiceConnection conn;
    private boolean isFile=true;
    @Override
    public void onCreate() {
        super.onCreate();
        // System.out.println("远程进程开启");
        init();
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                final List<StudentSign> studentSigns = CardDao.querySignId();
                final StringBuilder builder=new StringBuilder();
                builder.append("<RECORDS version=\"1.2\">\t \n");
                if (studentSigns.size()!=0){
                    for (StudentSign sign:studentSigns){
                        builder.append( "<ERRECORD>\n" +
                                "<CLOCKID>"+android.os.Build.SERIAL+"</CLOCKID>\n" +
                                "<CARDID>"+sign.getCardnum()+"</CARDID>\n" +
                                "<DATETIME>"+sign.getCardtime()+"</DATETIME> \n" +
                                "<BFLAG>2</BFLAG>\n" +
                                "</ERRECORD>\n");
                    }
                    builder.append("</RECORDS>");
                    Timecard(builder.toString(), new AsyncTaskSoapUtil.Callback() {
                        @Override
                        public void onPost(String data) {
                            if (data.equals("00")){
                                for (StudentSign sign:studentSigns){
                                    upSign(sign,0);
                                    builder.setLength(0);
                                }
                            }
                        }
                    });
                }
                String etherNetIP = AppUtlis.getEtherNetIP();
                if (etherNetIP.equals("0.0.0.0")){
                    try {
                        AppUtlis.down();
                        AppUtlis.up();
                        Intent intent=new Intent();
                        intent.setAction(Constant.ERR);
                        intent.putExtra(Constant.ERR,ClassCalendar.getIntDay()+"  IP:"+etherNetIP);
                        sendBroadcast(intent);
                    } catch (IOException e) {
                        Intent intent=new Intent();
                        intent.setAction(Constant.ERR);
                        intent.putExtra(Constant.ERR,"出错");
                        sendBroadcast(intent);
                        e.printStackTrace();
                    }
                }
                Heartbeat();
            }},1000,120000);

//        timer.schedule(new TimerTask() {
//            @Override
//            public void run() {
//
//            }
//        },1000,180000);
//        timer.schedule(new TimerTask() {
//            @Override
//            public void run() {
//
//            }
//        },3000,120000);
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                String packages = PrefUtild.INSTANCE.getString(getApplicationContext(), Constant.NPACKAGE, "");
                String packagesCode = PrefUtild.INSTANCE.getString(getApplicationContext(), Constant.CODE, "1");
                String app_no=android.os.Build.SERIAL;
                String is_encryption = PrefUtild.INSTANCE.getString(getApplicationContext(), Constant.ENCRYPTION, "");
                if (is_encryption.equals("1")){
                    String key = PrefUtild.INSTANCE.getString(getApplicationContext(), Constant.KEY, "");
                    String md5Value = AppUtlis.getMd5Value(app_no + key).toLowerCase();
//                    Log.e("ATG","key"+ key);
                    OkhttPost.Okget(API.NESPACKAES+"?app_no="+app_no+"&version_id="+ packagesCode +"&encryption_no="+md5Value+"&sno="+Constant.SNO+"&version_mini="+ packages,1,new RCall());

                }else{
                    OkhttPost.Okget(API.NESPACKAES+"?app_no="+app_no+"&version_id="+ packagesCode +"&sno="+Constant.SNO+"&version_mini="+ packages,1,new RCall());
                }
            }
        },4000,30000);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Intent intents = new Intent();
        intents.setClass(this, LocalService.class);
        bindService(intents, conn, Context.BIND_IMPORTANT);
        return START_STICKY;
    }

    private void init() {
        if (conn == null) {
            conn = new MyConnection();
        }
        binder = new MyBinder();
    }

    @Override
    public IBinder onBind(Intent intent) {
        return binder;
    }

    static class MyBinder extends IMyAidlInterface.Stub {


        @Override
        public String getName() throws RemoteException {
            return "远程连接";
        }
    }
    class RCall implements OkhttPost.Callback{

        @Override
        public void onError(Call call, Exception e, int id) {

        }

        @Override
        public void onResponse(String response, int id) {
            if (id==1){
                try {
                    Gson gson=new Gson();
                    VersionInfo versionInfo = gson.fromJson(response, VersionInfo.class);
                    if (versionInfo.code.equals("1")) {
                        if (!versionInfo.is_upload.equals("0")) {
                            if (isFile){
                                OkhttPost.OkFile(versionInfo.version_info.apk_url, new Claa());
                                PrefUtild.INSTANCE.setString(getApplicationContext(), "version_id", versionInfo.version_info.version_id);
                                PrefUtild.INSTANCE.setString(getApplicationContext(), "version_mini", versionInfo.version_info.version_mini);
                                isFile=false;
                            }
                            Log.e("ATG","版本更新 "+response);
                        }
                    }
                }catch (Exception e){}
            }
        }
    }
    class MyConnection implements ServiceConnection {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            System.out.println("获取远程连接");
        }

        @Override
        public void onServiceDisconnected(ComponentName nme) {
            RemoteService.this.startService(new Intent(RemoteService.this,
                    LocalService.class));
            RemoteService.this.bindService(new Intent(RemoteService.this,
                    LocalService.class), conn, Context.BIND_IMPORTANT);
        }
    }
    //打卡考勤
    public void Timecard(String str2,AsyncTaskSoapUtil.Callback callback){
        String time= ClassCalendar.getCardtime();

        String namespace = "http://www.gcihjt.com/";//namespace
        String methodName = "UploadSwingCards";//要调用的方法名称
        String WSDL_URI = "http://card.gcihjt.com/webcard.asmx";//wsdl 的uri
        Map<String,String> map=new HashMap<>();
        Log.e("debug",time);
        String md5="hjt"+time+"256B07301378445C83CB1A4D021FF4C7";
//        String md51 = AppUtlis.md5(md5);
        String md5Value = AppUtlis.getMd5Value(md5);
        Log.e("debug12",md5Value);
        map.put("Xml",str2);
        map.put("username","hjt");
        map.put("timeStr",time);
        map.put("hashCode",md5Value);
        AsyncTaskSoapUtil soapUtil=new AsyncTaskSoapUtil(namespace,WSDL_URI,methodName,map);
        soapUtil.setCallback(callback);
        soapUtil.execute();
    }
    public void Heartbeat(){
        String time= ClassCalendar.getCardtime();
        String namespace = "http://www.gcihjt.com/";//namespace http://www.gcihjt.com/
        String methodName = "Heartbeat";//要调用的方法名称
        String WSDL_URI = "http://card.gcihjt.com/webcard.asmx";//wsdl 的uri
        Map<String,String> map=new HashMap<>();
        map.put("machineNo",android.os.Build.SERIAL);
        map.put("username","hjt");
        map.put("timeStr",time);
        String md5Value = AppUtlis.getMd5Value("hjt"+time+"256B07301378445C83CB1A4D021FF4C7");
        map.put("hashCode",md5Value);
        AsyncTaskSoapUtil soapUtil=new AsyncTaskSoapUtil(namespace,WSDL_URI,methodName,map);
        soapUtil.setCallback(new AsyncTaskSoapUtil.Callback() {
            @Override
            public void onPost(String data) {
                if (data.equals("00")){
                    Log.e("ATG","心跳包成功");
                    Intent intent=new Intent();
                    intent.setAction(Constant.ERR);
                    intent.putExtra(Constant.ERR,ClassCalendar.getStringtHour()+": 心跳包成功");
                    sendBroadcast(intent);
//                    MainActivity.initialList.add("心跳包成功");
                }else {
                    Intent intent=new Intent();
                    intent.setAction(Constant.ERR);
                    intent.putExtra(Constant.ERR,ClassCalendar.getStringtHour()+":心跳包失败 "+data);
                    sendBroadcast(intent);
//                    MainActivity.initialList.add("心跳包失败"+data);
                }
            }
        });
        soapUtil.execute();
    }
    public void upSign(StudentSign cardStudent,int type){
        StudentSign sign = new StudentSign(cardStudent.getId(), ClassCalendar.getStringMinuts(),type,ClassCalendar.getCardtime(),cardStudent.getCardnum());
        CardDao.updateSign(sign);
        BaseApplication.getDaoInstant().clear();
    }
    class Claa implements OkhttPost.FileCallBack {
        @Override
        public void onError(Call call, Exception e, int id) {
            isFile=true;
        }
        @Override
        public void onResponse(File response, int id) {
            PrefUtild.INSTANCE.setString(getApplicationContext(),Constant.GETUP,"1");
            AppUtlis.installNormal(RemoteService.this,response.getAbsolutePath());
            isFile=true;
        }
    }

}